<template>
  <div id="app" ref="sparePartCheckRef" tabindex="0" class="spare-part-check">
    <van-nav-bar left-arrow title="备件盘库" @click-left="comeBack" left-text="返回">
      <template #right>
        <van-icon size="1.5rem" name="plus" @click="showCheckPopFn" />
      </template>
    </van-nav-bar>

    <!-- 历史查询 -->
    <van-search v-model="queryParam.queryParam" @search="filterDataFn()"></van-search>

    <van-popup style="width: 90vw;padding: 1vh 2vw;max-height: 80vh;overflow: auto;" v-model="showCheck" get-container="#app">
      <!-- 主表单 -->
      <van-form validate-first validate-trigger="onSubmit" @submit="confirmCheckFn">
        <van-field label="类型" colon clearable readonly placeholder="请选择类型" v-model="checkData.type" @focus="() => filterDataFn(1, 100)"></van-field>
        <van-field label="车间" colon clearable readonly placeholder="请选择车间" v-model="checkData.room" @focus="() => filterDataFn(2, 100)"></van-field>
        <van-field label="设备用途" colon clearable placeholder="请输入或选择设备用途" v-model="checkData.device" :rules="[{ validator: validatorFn, message: '请输入或选择设备用途' }]">
          <template #button>
            <van-button type="info" native-type="button" size="small" @click="filterDataFn(3, 100)">筛选</van-button>
          </template>
        </van-field>
        <van-field label="供应商" colon clearable placeholder="请输入或选择供应商" v-model="checkData.supplier" :rules="[{ validator: validatorFn, message: '请输入或选择供应商' }]">
          <template #button>
            <van-button type="info" native-type="button" size="small" @click="filterDataFn(4, 100)">筛选</van-button>
          </template>
        </van-field>
        <van-field label="名称" colon clearable placeholder="请输入或选择名称" v-model="checkData.name" :rules="[{ validator: validatorFn, message: '请输入或选择供应商' }]" @input="checkData.partId = 0">
          <template #button>
            <van-button type="info" native-type="button" size="small" @click="filterDataFn(5, 100)">筛选</van-button>
          </template>
        </van-field>
        <van-field label="型号规格" colon clearable placeholder="请输入规格型号" v-model="checkData.standard">
        </van-field>
        <van-field label="区域" colon clearable placeholder="请输入或选择区域" v-model="checkData.area" :rules="[{ validator: validatorFn, message: '请输入或选择区域' }]" @input="checkData.areaId = 0">
          <template #button>
            <van-button type="info" native-type="button" size="small" @click="filterDataFn(6, 100)">筛选</van-button>
          </template>
        </van-field>
        <van-field label="单位" colon clearable readonly placeholder="请选择单位" v-model="checkData.unit" @focus="() => filterDataFn(7, 100)"></van-field>
        <van-field label="回收标记" colon clearable readonly placeholder="请选择回收标记" v-model="checkData.recyclingFlag" @focus="() => filterDataFn(8, 100)"></van-field>
        <van-field label="预计库存" colon clearable placeholder="请输入预计库存" v-model="checkData.expectStock" :rules="[{ validator: validatorFn, message: '请输入预计库存' }]"></van-field>
        <van-field label="库存" colon clearable placeholder="请输入库存" v-model="checkData.stock" :rules="[{ validator: validatorFn, message: '请输入库存' }]"></van-field>
        <van-uploader style="margin: 10px" preview-size="80vw" v-model="uploadFileList" :max-count="5"></van-uploader>
        <div style="margin: 16px;display: flex;justify-content: center;width: 90%;">
          <van-button block type="info" native-type="submit">确认并打印</van-button>
        </div>
      </van-form>
    </van-popup>

    <!-- 滚动 -->
    <better-scroll class="body-scroll" :data="sparePartCheckData" :total-page="totalPage" :pulldown="true" :pullup="true" @pullup="loadNextPageFn" @pulldown="() => loadSparePartCheckDataFn(1)">
      <van-swipe-cell v-show="sparePartCheckData.length > 0" v-for="(row, rIndex) in sparePartCheckData" :key="row.id" style="padding-bottom: 0.5rem">
        <template>
          <div class="data-card">
            <div style="flex: 1; flex-flow: column;">
              <div style="border-bottom: 1px solid #8191c5;" >
                <span style="color: #8191c5;font-size: 1.2rem; ">{{ row.name }}</span>
              </div>
              <div>
                <span style="color: #bb5a09;font-size: 1.1rem; ">{{ row.standard == SPLIT_BLANK ? "无规格" : row.standard }}</span>
              </div>
              <div>
                <span style="color: #232323;font-size: 1rem; ">{{ row.device }}</span>
              </div>
              <div style="justify-content: space-between">
                <span style="color: #e6a23c">预计库存: {{ row.expectStock }} {{row.unit}}</span>
                <van-popover theme="dark" v-model="row.showArea" trigger="click" :actions="row.areas" placement="bottom-end" get-container="#app">
                  <template #reference>
                    <span style="color: #239a2a">库存: {{ row.stock }} {{row.unit}}</span>
                  </template>
                </van-popover>
              </div>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square size="small" type="primary" @click="rePrintFn(row)">再次打印</van-button>
          </div>
        </template>
      </van-swipe-cell>
      <van-empty  v-show="sparePartCheckData.length == 0" image="https://img01.yzcdn.cn/vant/custom-empty-image.png" description="暂无数据" ></van-empty>
    </better-scroll>

    <!-- 弹出面板 -->
    <van-action-sheet v-model="showActionSheet" :actions="actionSheetData" title="请选择" cancel-text="取消" close-on-click-action get-container="#app" @cancel="showActionSheet = false" @select="selectFilterDataFn"></van-action-sheet>
  </div>
</template>

<script>
import {comeBack, deepCopy} from "@/utils";
import {getInfo, getMacAddress} from "@/utils/auth";
import {
  changeSparePartPic, checkSparePart, filterSpareArea,
  filterSpareDevice,
  filterSpareSupplier, loadSparePartCheckData,
  loadSparePartData
} from "@/views/spare-part/spare-part.js";
import {
  SPARE_PART_ROOM_ENUM,
  SPARE_PART_TYPE_ENUM,
  UNIT_ENUM,
  sparePartRoomEnumFn,
  sparePartTypeEnumFn,
  unitEnumFn,
  SPLIT_BLANK,
  SPLIT_COMMA, SPARE_PART_RECYCLING_ENUM, sparePartRecyclingEnumFn
} from "@/api/enum";
import {getUploadKey} from "@/api/public";
import {exportBaseUrl} from "@/utils/request";
import {picUpload} from "@/api/common";
import dayjs from "dayjs";

export default {
  name: "sparePartCheck",
  data() {
    return {
      SPLIT_BLANK,
      /* 查询相关 */
      queryParam: {
        yarnNo: "",
        pageNum: 1,
        pageSize: 6,
        optFlag: 1,
      },
      queryTimer: null,
      showActionSheet: false,
      actionSheetData: [],

      /* 盘库对象 */
      showCheck: false,
      checkData: {
        id: 0,
        partId: 0,
        type: SPLIT_BLANK,
        room: SPLIT_BLANK,
        device: SPLIT_BLANK,
        supplier: SPLIT_BLANK,
        name: SPLIT_BLANK,
        standard: SPLIT_BLANK,
        area: SPLIT_BLANK,
        unit: SPLIT_BLANK,
        recyclingFlag: "1",
        expectStock: 0,
        stock: 0,
        pic: SPLIT_BLANK,
      },

      /* 列表相关 */
      sparePartCheckData: [],
      totalPage: 0,
      uploadFileList: [],
      curRow: null,

      /* 图片相关 */
      picType: "WLBJ",
      showChangePicDialog: false,
      showPicPreViewFlag: false,
      picPreView: [],


      /* 打印相关 */
      printCount: 1,
      printStatus: false,
      connectionStatus: false,
    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }

    // that.initFn(that);   //dev fixme
  },
  methods: {
    comeBack,

    /* 初始化 */
    initFn() {
      const that = this;
      if (getMacAddress()) {
        that.isEnabledBluetooth();
      } else {
        that.$toast.fail('如需打印，请退出登录选择打印机')
      }

      //加载盘库数据
      that.loadSparePartCheckDataFn(1);
    },

    /* 显示盘库弹框 */
    showCheckPopFn() {
      const that = this;
      that.checkData.id = 0;
      that.checkData.partId = 0;
      that.checkData.type = SPLIT_BLANK;
      that.checkData.room = SPLIT_BLANK;
      that.checkData.device = SPLIT_BLANK;
      that.checkData.supplier = SPLIT_BLANK;
      that.checkData.name = SPLIT_BLANK;
      that.checkData.standard = SPLIT_BLANK;
      that.checkData.area = SPLIT_BLANK;
      that.checkData.unit = SPLIT_BLANK;
      that.checkData.recyclingFlag = "1";
      that.checkData.expectStock = 0;
      that.checkData.stock = 0;
      that.checkData.pic = SPLIT_BLANK;
      that.uploadFileList.splice(0, that.uploadFileList.length);
      that.showCheck = true;
    },

    /* 显示预览图 */
    showPicPreViewFn(row) {
      const that = this;
      that.picPreView.splice(0, that.picPreView.length);
      row.pic.split(SPLIT_COMMA).forEach(pic => {
        getUploadKey({
          type: that.picType
        }, tokenRes => {
          that.picPreView.push(exportBaseUrl("res") + "/res/" + pic + '?accessToken=' + tokenRes.accessToken);
        });
      });
      that.showPicPreViewFlag = true;
    },

    /* 校验 */
    validatorFn(val, rule) {
      const that = this;
      let result = val != "";
      if(!result) {
        that.$toast.fail(rule.message);
      }
      return result;
    },

    /* 筛选数据 */
    filterDataFn(optFlag, timer) {
      const that = this;
      that.queryParam.optFlag = optFlag;
      clearTimeout(that.queryTimer);
      that.queryTimer = setTimeout(() => {
        that.$refs.sparePartCheckRef.focus();
        that.actionSheetData.splice(0, that.actionSheetData.length);
        if (1 == optFlag) {
          Object.keys(SPARE_PART_TYPE_ENUM).forEach(key => {
            that.actionSheetData.push({
              name: sparePartTypeEnumFn(key)
            });
          });
          that.showActionSheet = true;
        } else if(2 == optFlag) {
          Object.keys(SPARE_PART_ROOM_ENUM).forEach(key => {
            that.actionSheetData.push({
              name: sparePartRoomEnumFn(key)
            });
          });
          that.showActionSheet = true;
        } else if(3 == optFlag) {
          filterSpareDevice({
            keyLike: that.checkData.device
          }, data => {
            data.forEach(item => {
              that.actionSheetData.push({
                name: item
              });
            });
          });
          that.showActionSheet = true;
        } else if(4 == optFlag) {
          filterSpareSupplier({
            keyLike: that.checkData.supplier
          }, data => {
            data.forEach(item => {
              that.actionSheetData.push({
                name: item
              });
            });
          });
          that.showActionSheet = true;
        } else if(5 == optFlag) {
          loadSparePartData({
            keyLike: that.checkData.name,
          }, data => {
            data.list.forEach(item => {
              that.actionSheetData.push({
                name: item.name,
                item: item
              });
            });
          });
          that.showActionSheet = true;
        } else if(6 == optFlag) {
          filterSpareArea({
            keyLike: that.checkData.area
          }, data => {
            data.forEach(item => {
              that.actionSheetData.push({
                name: item,
              });
            });
          });
          that.showActionSheet = true;
        } else if(7 == optFlag) {
          Object.keys(UNIT_ENUM).forEach(key => {
            that.actionSheetData.push({
              name: unitEnumFn(key)
            });
          });
          that.showActionSheet = true;
        } else if(8 == optFlag) {
          Object.keys(SPARE_PART_RECYCLING_ENUM).forEach(key => {
            that.actionSheetData.push({
              name: sparePartRecyclingEnumFn(key)
            });
          });
          that.showActionSheet = true;
        }
      }, timer? timer : 2000);
    },

    /* 选择数据 */
    selectFilterDataFn(action) {
      let item = action.item;
      const that = this;
      if(1 == that.queryParam.optFlag) {
        that.checkData.type = action.name;
      } else if(2 == that.queryParam.optFlag) {
        that.checkData.room = action.name;
      } else if(3 == that.queryParam.optFlag) {
        that.checkData.device = action.name;
      } else if(4 == that.queryParam.optFlag) {
        that.checkData.supplier = action.name;
      } else if (5 == that.queryParam.optFlag) {
        that.checkData.partId = item.id;
        that.checkData.type = SPARE_PART_TYPE_ENUM[item.type];
        that.checkData.room = SPARE_PART_ROOM_ENUM[item.room];
        that.checkData.device = item.device;
        that.checkData.supplier = item.supplier;
        that.checkData.name = item.name;
        that.checkData.standard = item.standard;
        that.checkData.unit = item.unit;
        that.checkData.recyclingFlag = SPARE_PART_RECYCLING_ENUM[item.recyclingFlag];
      } else if(6 == that.queryParam.optFlag) {
        that.checkData.area = action.name;
      } else if(7 == that.queryParam.optFlag) {
        that.checkData.unit = action.name;
      } else if(8 == that.queryParam.optFlag) {
        that.checkData.recyclingFlag = action.name;
      }
    },

    /* 确认盘库 */
    confirmCheckFn() {
      const that = this;
      if(that.checkData.stock < 0) {
        that.$toast.fail("库存不能小于0");
        return
      }
      if(that.uploadFileList.length > 0) {
        //上传图片
        picUpload(that, that.uploadFileList, res => {
          let tmpArray = that.uploadFileList.filter(uploadFile => uploadFile.name).map(uploadFile => uploadFile.name);
          tmpArray.push(res.data);
          that.checkData.pic = tmpArray.join(SPLIT_COMMA);
          that.confirmCheckSubFn();
        });
      } else {
        that.confirmCheckSubFn();
      }
    },
    confirmCheckSubFn() {
      const that = this;
      let params = deepCopy(that.checkData);
      params.type = sparePartTypeEnumFn(null, params.type);
      params.room = sparePartRoomEnumFn(null, params.room);
      params.recyclingFlag = sparePartRecyclingEnumFn(null, params.recyclingFlag);
      checkSparePart(params, data => {
        that.$toast.success("确认成功");
        that.checkData.id = data.id;
        that.checkData.optName = getInfo().realName;
        that.printLabel(data);
      });
    },


    /* 加载备件 */
    loadSparePartCheckDataFn(pageNum) {
      const that = this;
      if(pageNum == 1) {
        that.queryParam.pageNum = 1;
        that.sparePartCheckData.splice(0, that.sparePartCheckData.length);
      }
      loadSparePartCheckData(that.queryParam, data => {
        if(!data.code && data.code != 0) {
          that.totalPage = data.totalPage;
          data.list.forEach(row => {
            that.fillPicViewFn(that, row);
            that.sparePartCheckData.push(row);
          });
        }
      });
    },
    /* 填充图片 */
    fillPicViewFn(that, row) {
      row.picView = SPLIT_BLANK;
      getUploadKey({
        type: that.picType
      }, tokenRes => {
        row.picView = exportBaseUrl("res") + "/res_thumb/" + row.pic.split(SPLIT_COMMA)[0] + '?accessToken=' + tokenRes.accessToken;
      });
    },

    /* 加载下一页 */
    loadNextPageFn() {
      let that = this;
      that.queryParam.pageNum++;
      that.loadSparePartCheckDataFn();
    },

    /* 重新打印 */
    rePrintFn(row) {
      const that = this;
      that.printLabel(row);
    },

    /* 判断蓝牙是否打开 */
    isEnabledBluetooth() {
      const that = this;
      window.api.require("cxgBluetoothBase").isEnabledBluetooth({}, (ret, err) => {
        if (!err) {
          if (ret.state) {
            // 已打开
            that.connectBleByMacAddress();
          } else {
            that.openBluetooth();
          }
        } else {
          that.$toast.fail("code: " + err.code + " msg: " + err.msg);
        }
      });
    },
    /* 打开蓝牙 */
    openBluetooth() {
      const that = this;
      window.api.require("cxgBluetoothBase").openBluetooth({}, function (ret, err) {
        if (!err) {
          if (ret.state) {
            // 已打开
            that.connectBleByMacAddress();
          }
        } else {
          that.listenBluetoothStatus();
        }
      });
    },
    /* 监听蓝牙连接状态 */
    listenBluetoothStatus() {
      const that = this;
      window.api.require("cxgBluetoothBase").listenBluetoothStatus({}, function (ret, err) {
        if (!err) {
          if (ret.status === "STATE_ON") {
            that.connectBleByMacAddress();
          }
        } else {
          that.$toast.fail("code: " + err.code + " msg: " + err.msg);
        }
      });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      let obj = window.api.require("xGprinterPlus");
      let ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    /* 连接蓝牙 */
    connectBleByMacAddress(status) {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      let demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress({
        macAddress:  getMacAddress() ? getMacAddress().address : '',
      }, (ret, err) => {
        if (ret.status) {
          if (ret.message === "已连接") {
            that.connectionStatus = true;
            if (that.printStatus) {
              that.$toast({
                type: "success",
                message: "连接成功",
                duration: 1500,
              });
            }
            if (status) {
              // that.onClickAddStore();    //新增盘库?
            }
          } else if (ret.message === "连接失败") {
            that.connectionStatus = false;
            that.$toast({
              type: "fail",
              message: "初始化失败",
              duration: 1500,
            });
          } else {
            that.connectionStatus = false;
          }
        } else {
          that.$toast({
            type: "fail",
            message: err.msg,
            duration: 1500,
          });
        }
      });
    },

    /* 打印数据 */
    printLabel(checkData) {
      const that = this;
      let obj = window.api.require("xGprinterPlus");
      let rows = [{
        lineType: "size",
        width: 50,
        height: 70,
      }, {
        lineType: "gap",
        data: 3,
      }, {
        lineType: "cls",
      }, {
        // 图片单元格竖线
        lineType: "bar",
        x: 25 + 150,
        y: 0,
        width: 2,
        height: 136,
      }, {
        //绘制图片
        lineType: "image",
        x: 25 + 8,
        y: 8,
        data: "widget://image/huibo_logo.png",
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 8,
        y: 10,
        rotation: 0,
        xscal: 1,
        yscal: 1,
        data: "艺多染整",
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 8,
        y: 60,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "备件规格码",
      }, {
        lineType: "qrcode", // 绘制qrcode
        x: 25 + 170 + 2,
        y: 10,
        level: "L", //L|M|H|Q
        cellwith: 8,
        rotation: 0, // 0|90|180|270
        data: "33," + checkData.partId,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 136 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "ID:" + checkData.partId,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 186,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 186 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "类型: " + SPARE_PART_TYPE_ENUM[checkData.type],
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 236,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 236 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "车间:" + SPARE_PART_ROOM_ENUM[checkData.room],
      }, {
        //绘制文本
        lineType: "text",
        x: 300 + 4,
        y: 236 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: SPARE_PART_RECYCLING_ENUM[checkData.recyclingFlag],
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 286,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 286 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "用途: " + checkData.device,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 336 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "名称: " + checkData.name,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 336,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 386 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "规格: " + checkData.standard,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 386,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 436 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "打印人: " + checkData.optName,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 436,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 516 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 1,
        data: "打印日期: " + dayjs().format("YYYY-MM-DD"),
      },];
      obj.printLabel({
        rows: rows,
      }, (ret, err) => {
        if (ret.status) {
          that.$toast.success("打印成功");
          --that.printCount;
          if (that.printCount > 0) {
            that.printLabel(checkData);
          } else {
            that.printCount = 1;

            //关闭盘库窗口
            that.showCheck = false;
          }
        } else {
          that.$toast({
            type: "fail",
            message: err.code + err.msg,
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.spare-part-check {
  ::v-deep .van-search {
    z-index: 1;
  }

  .body-scroll {
    height: 79vh;
    .data-card {
      width: 96vw;
      padding: 0 0.8rem;
      margin-left: 2vw;
      background-color: white;
      margin-top: 0.5rem;
      box-shadow: 0.3rem 0.5rem 0.3rem #888888;
      display: flex;
      div {
        display: flex;
        padding: 0.3rem 0rem;
        span {
          line-height: 1rem;
        }
      }
    }
  }
}
</style>